package stream.part5;


import org.apache.commons.compress.utils.Lists;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupingByTest {
    public static void main(String[] args) {
        Product prod1 = new Product(1L, 1, new BigDecimal("15.5"), "面包", "零食");
        Product prod2 = new Product(2L, 2, new BigDecimal("20"), "饼干", "零食");
        Product prod3 = new Product(3L, 3, new BigDecimal("30"), "月饼", "零食");
        Product prod4 = new Product(4L, 3, new BigDecimal("10"), "青岛啤酒", "啤酒");
        Product prod5 = new Product(5L, 10, new BigDecimal("15"), "百威啤酒", "啤酒");
        List<Product> list = new ArrayList<>();
        list.add(prod1);
        list.add(prod2);
        list.add(prod3);
        list.add(prod4);
        list.add(prod5);

        Map<String, List<Product>> collect = list.stream().collect(Collectors.groupingBy(Product::getCategory));

        Map<String, List<Product>> collect1 = list.stream().collect(Collectors.groupingBy(new Function<Product, String>() {
            @Override
            public String apply(Product product) {
                return product.getCategory() + "_" + product.getName();
            }
        }));
        System.out.println(collect1);
        /**
         * 多级分组
         */

        Map<String, Map<String, List<Product>>> collect2 = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.groupingBy(product -> {
            if (product.getNum() >= 3) {
                return "多";
            } else {
                return "少";
            }
        })));
        System.out.println(collect2);
        /**
         * 按子组收集数据
         */

        Map<String, Long> collect3 = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));
        System.out.println(collect3);
        /**
         * 按子组求和
         */
        Map<String, Integer> collect4 = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summingInt(Product::getNum)));

        System.out.println(collect4);

        /**
         * 联合其他收集器   后面的参数是对分组后的记过进行处理
         */
        Map<String, Set<String>> prodMap = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.mapping(Product::getName, Collectors.toSet())));

        System.out.println(prodMap);


        Map<String, Double> collect5 = list.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.averagingInt(Product::getNum)));


        System.out.println(collect5);


    }
}



